//请实现一个函数，把字符串 s 中的每个空格替换成"%20"。 
//
// 
//
// 示例 1： 
//
// 输入：s = "We are happy."
//输出："We%20are%20happy." 
//
// 
//
// 限制： 
//
// 0 <= s 的长度 <= 10000 
// Related Topics 字符串 👍 275 👎 0


package leetcode.editor.cn;

//Java：替换空格
public class TiHuanKongGeLcof {
    public static void main(String[] args) {
        Solution solution = new TiHuanKongGeLcof().new Solution();
        // TO TEST
        System.out.println(solution.replaceSpace("We are happy."));
        System.out.println(solution.replaceSpace("Hi, John. I'm John from China..."));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        // 把字符串 s 中的每个空格替换成"%20"
        public String replaceSpace(String s) {
            // 计算有多少个空格
            int spaceLen = 0;
            char[] chars = s.toCharArray();
            int clen = chars.length;
            for (int i = 0; i < clen; i++) {
                if (chars[i] == ' ') {
                    spaceLen++;
                }
            }
            char[] targets = new char[clen + 2 * spaceLen];
            int j = 0;
            for (int i = 0; i < clen; i++) {
                if (chars[i] == ' ') {
                    targets[j++] = '%';
                    targets[j++] = '2';
                    targets[j++] = '0';
                } else {
                    targets[j++] = chars[i];
                }
            }
            return new String(targets);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
